﻿using AutoMapper;
using PowerHub.MES.Common.NumberingCenter;
using PowerHub.MES.DTO.Shopfloor.DTO;
using PowerHub.MES.DTO.Shopfloor.QueryDTO;
using PowerHub.MES.EFBase;
using PowerHub.MES.Entities.Shopfloor;
using PowerHub.MES.Entities;
using PowerHub.MES.IRepository.IShopfloor;
using PowerHub.MES.IServices.IShopfloor;
using PowerHub.MES.Jwt;
using PowerHub.MES.ReturnEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PowerHub.MES.Entities.Crew;
using PowerHub.MES.DTO.Crew.QueryDto;
using PowerHub.MES.DTO.Crew.DTO;
using PowerHub.MES.IServices.ICrew;
using PowerHub.MES.IRepository.ICrew;
using Microsoft.IdentityModel.Tokens;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using PowerHub.MES.Controllers.Crew;

namespace PowerHub.MES.Services.Crew
{
    /// <summary>
    /// 排班计划接口实现层
    /// </summary>
    public class Crew_SchedulingPlanServices : BaseServices<Crew_SchedulingPlan>, ICrew_SchedulingPlanServices
    {
        private ICrew_SchedulingPlanRepository _iCrew_SchedulingPlanRepository;
        private ICrew_SchedulingPlanDetialRepository _ICrew_SchedulingPlanDetialRepository;
        public UserServices _userServices;
        private IMapper _mapper;

        public Crew_SchedulingPlanServices(PowerHubMesContext powerHubMesContext, ICrew_SchedulingPlanRepository iCrew_SchedulingPlanRepository,
            UserServices userServices, IMapper mapper, ICrew_SchedulingPlanDetialRepository crew_SchedulingPlanDetialRepository) : base(powerHubMesContext)
        {
            _ICrew_SchedulingPlanDetialRepository = crew_SchedulingPlanDetialRepository;
            _iCrew_SchedulingPlanRepository = iCrew_SchedulingPlanRepository;
            _userServices = userServices;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取排班计划列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationPageResult<List<Crew_SchedulingPlan>>> GetCrew_SchedulingPlanPageListAsync(QueryCrew_SchedulingPlanDTO query)
        {
            return await _iCrew_SchedulingPlanRepository.GetCrew_SchedulingPlanPageListAsync(query);
        }

        /// <summary>
        /// 添加排班计划
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationResult<bool>> CreateCrew_SchedulingPlanAsync(Crew_SchedulingPlanDTO query)
        {
            Crew_SchedulingPlan foundation = await GetEntityAsync(d => d.SchedulingPlanName.Equals(query.SchedulingPlanName) && d.IsDel == 0);
            if (foundation != null)
            {
                throw new Exception("你输入的排班计划名称已存在！");
            }
            if (string.IsNullOrEmpty(query.TeamBillId))
            {
                throw new Exception("请选择班组");
            }
            if (string.IsNullOrEmpty(query.ProductionLineId))
            {
                throw new Exception("请选择产线！");
            }


            //实体转换
            var Crew_SchedulingPlan = _mapper.Map<Crew_SchedulingPlan>(query);
            Crew_SchedulingPlan.Id = Guid.NewGuid().ToString();
            Crew_SchedulingPlan.SchedulingPlanNo = string.IsNullOrEmpty(query.SchedulingPlanNo) || query.SchedulingPlanNo.Contains(" ") ? GenerateBasicDataNO.GenerateCode(query.SchedulingPlanName) : query.SchedulingPlanNo;
            Crew_SchedulingPlan.Creator = _userServices.UserName;

            int i = 0;
            foreach (var item in Crew_SchedulingPlan.CrewSchedulingPlanDetials)
            {
                i++;
                if (string.IsNullOrEmpty(item.UserinfoId))
                {
                    throw new Exception("获取班组人员异常，请重新选择班组后试试");
                }
                if (string.IsNullOrEmpty(item.WorkStationId) && item.Status < 1)
                {
                    throw new Exception($"第 {i} 行，还未设置工作站台，请检查！");
                }
                item.Id = Guid.NewGuid().ToString();
                item.Creator = _userServices.UserName;
                item.Crew_SchedulingPlanId = Crew_SchedulingPlan.Id;
            }
            return await _iCrew_SchedulingPlanRepository.CreateCrew_SchedulingPlanAsync(Crew_SchedulingPlan);
        }


        /// <summary>
        /// 批量删除排班计划
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationResult<bool>> DeletionCrew_SchedulingPlanAsync(List<string>? ids)
        {
            if (ids.Count < 1)
            {
                throw new Exception("请先选择数据！");
            }
            return await _iCrew_SchedulingPlanRepository.DeletionCrew_SchedulingPlanAsync(ids);
        }


        /// <summary>
        /// 更新排班计划
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationResult<bool>> UpdateCrew_SchedulingPlanAsync(Crew_SchedulingPlanDTO query)
        {
            if (query == null)
            {
                throw new Exception("请先选择数据！");
            }
            if (string.IsNullOrEmpty(query.Id))
            {
                throw new Exception("更新失败，找不到当前计划！");
            }

            //根据id获取排班计划信息
            Crew_SchedulingPlan Crew_SchedulingPlan = await GetEntityAsync(d => d.Id.Equals(query.Id));
            if (Crew_SchedulingPlan == null)
            {
                throw new Exception("更新排班计划信息发生了异常,请刷新页面后试试");
            }
            if (Crew_SchedulingPlan!=null)
            {
                Crew_SchedulingPlan.SchedulingPlanName = query.SchedulingPlanName;
                Crew_SchedulingPlan.ProductionLineId = query.ProductionLineId;
                Crew_SchedulingPlan.StartTime = query.StartTime;
                Crew_SchedulingPlan.SchedulingPlanStatus = query.SchedulingPlanStatus;
                Crew_SchedulingPlan.ShiftPattern = query.ShiftPattern;
                Crew_SchedulingPlan.EndTime = query.EndTime;
                Crew_SchedulingPlan.Updator = _userServices.UserName;

            }

            return await _iCrew_SchedulingPlanRepository.UpdateCrew_SchedulingPlanAsync(Crew_SchedulingPlan);

        }

        /// <summary>
        /// 根据班组id获取排班计划明细列表
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<OperationPageResult<List<Crew_SchedulingPlanDetial>>> GetCrew_SchedulingPlanByIdDetialsPageListAsync(QueryCrew_SchedulingPlanDTO pageQuery)
        {
            return await _ICrew_SchedulingPlanDetialRepository.GetCrew_SchedulingPlanDetialPageListAsync(pageQuery);
        }

        /// <summary>
        /// 根据班组id获取排班计划
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<OperationResult<Crew_SchedulingPlanUpdateDto>> GetCrew_SchedulingPlanByIdAsync(QueryCrew_SchedulingPlanDTO pageQuery)
        {
            var result = new OperationResult<Crew_SchedulingPlanUpdateDto>();
            var Crew_SchedulingPlan = await _iCrew_SchedulingPlanRepository.GetCrew_SchedulingPlanByIdAsync(pageQuery);

            //头
            var schedulingPlanDto = _mapper.Map<Crew_SchedulingPlanUpdateDto>(Crew_SchedulingPlan);
            schedulingPlanDto.TeamName = Crew_SchedulingPlan.TeamBill.TeamName;
            schedulingPlanDto.ProductionLineName = Crew_SchedulingPlan.ProductionLine.ProductionLineName;

            //明细
            schedulingPlanDto.CrewSchedulingPlanDetial = Crew_SchedulingPlan.CrewSchedulingPlanDetials.Select(g => new CrewSchedulingPlanDetialsDtos()
            {
                Id = g.Id,
                Crew_SchedulingPlanId = g.Crew_SchedulingPlanId,
                UserinfoId = g.UserinfoId,
                JobNumber = g.Userinfo.JobNumber,
                UserName = g.Userinfo.UserName,
                DepartmentName = g.Userinfo.Department.DepartmentName,
                WorkStationId = g.WorkStation != null ? g.WorkStation.Id:null,
                WorkStationName = g.WorkStation != null ? g.WorkStation.WorkStationName:null,
                ProcessName = g.WorkStation!=null? g.WorkStation.Process.ProcessName:null,
                Status = g.Status
            }).ToList();

            result.Data= schedulingPlanDto;
            return result;
        }

        /// <summary>
        /// 根据明细id更新排班计划明细
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<OperationResult<bool>> UpdateCrew_SchedulingPlanDetialByIdAsync(CrewSchedulingPlanDetialsDtos query)
        {
            if (query==null)
            {
                throw new Exception("更新工作站台错误，请重新试试");
            }
            //if (string.IsNullOrEmpty(query.WorkStationId))
            //{
            //    throw new Exception("工作站台为空！");
            //}
            if (string.IsNullOrEmpty(query.Id))
            {
                throw new Exception("打不到当前员工信息！");
            }

            return await _ICrew_SchedulingPlanDetialRepository.UpdateCrew_SchedulingPlanDetialByIdAsync(query);

        }


        /// <summary>
        /// 根据计划Id绑定工单
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<OperationResult<bool>> UpdateCrew_SchedulingPlanByBindWorkOrderAsync(Crew_SchedulingPlanBindDTO query)
        {
            if (string.IsNullOrEmpty(query.WorkOrderId))
            {
                throw new Exception("绑定工单失败！");
            }
            
            //获取计划信息
            var schedulingPlan= await this.GetEntityAsync(g=>g.Id.Equals(query.SchedulingPlanId));
            if (schedulingPlan==null) { 
                
                throw new Exception("找不到当前计划信息，你重新打开分配页面！");
            }
            schedulingPlan.WorkOrderId=query.WorkOrderId;
            schedulingPlan.Updator=_userServices.UserName;

            return await _iCrew_SchedulingPlanRepository.UpdateCrew_SchedulingPlanByBindWorkOrderAsync(schedulingPlan);
        }
    }
}
